package com.ysw.rpc.client.config;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.NacosServiceManager;
import com.ysw.rpc.client.component.ChannelComponent;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * @author YinShangwen
 * @since 2023/4/18 15:51
 */
public class NacosServiceRegistryBeanPostProcess implements BeanPostProcessor, ApplicationContextAware {
    private ApplicationContext applicationContext;

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        String registerBeanName = "nacosServiceRegistry";
        if (registerBeanName.equals(beanName)) {
            NacosServiceManager nacosServiceManager = applicationContext.getBean(NacosServiceManager.class);
            NacosDiscoveryProperties nacosDiscoveryProperties = applicationContext.getBean(NacosDiscoveryProperties.class);
            ClientProperties clientProperties = applicationContext.getBean(ClientProperties.class);
            ChannelComponent channelComponent = applicationContext.getBean(ChannelComponent.class);
            return new ClientInitializerConfig(nacosServiceManager, nacosDiscoveryProperties, clientProperties, channelComponent);
        }
        return bean;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
